package com.buaa.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.buaa.common.R;
import com.buaa.common.Result;
import com.buaa.entity.User;
import com.buaa.entity.UserActivity;
import com.buaa.enums.ResponseCode;
import com.buaa.enums.OperationType;
import com.buaa.service.impl.UserActivityServiceImpl;
import com.buaa.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserServiceImpl userServiceImpl;

    @Autowired
    private UserActivityServiceImpl userActivityServiceImpl;

    // 新增
    @PostMapping
    public R save(@RequestBody User user, HttpServletRequest request) {
        if (null == user || (null != user && null == user.getPoliceId()))
            return R.error("交警编号为空！");

        User currentOpUser = userServiceImpl.getOperateUser(request);
        boolean r =  userServiceImpl.saveOrUpdate2(user, currentOpUser);
        if (r) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("police_id", user.getPoliceId());
            user = userServiceImpl.getOne(queryWrapper);
            UserActivity userActivity = new UserActivity();
            BeanUtil.copyProperties(user, userActivity, true);
            userActivity.setUid(user.getId());
            Integer id = null;
            userActivity.setId(id);
            userActivity.setOperationType(OperationType.USER_ADD.getDesc());
            userActivityServiceImpl.save(userActivity);
        }
        return r ? R.ok("创建交警账号成功.") : R.error("创建交警账号失败.");
    }

    /**
     * 根据ID删除交警账号。
     *
     * @param id 交警账号的ID，不能为空。
     * @return 返回操作结果，成功删除返回包含成功消息的R对象，失败返回包含错误消息的R对象。
     */
    @DeleteMapping("{id}")
    public R deleteById(@PathVariable("id") Integer id, HttpServletRequest request){
        // 根据ID删除账号，返回操作结果
        // 删除前先记录log
        User user = userServiceImpl.getById(id);
        if (null == user)
            return R.error("交警账号不存在.");

        User currentOpUser = userServiceImpl.getOperateUser(request);

        UserActivity userActivity = new UserActivity();
        BeanUtil.copyProperties(user, userActivity, true);
        userActivity.setUid(user.getId());
        Integer ids = null;
        userActivity.setId(ids);
        userActivity.setOperationType(OperationType.USER_DELETE.getDesc());
        userActivity.setReviser(currentOpUser.getUserName());
        userActivity.setRevisionTime(LocalDateTime.now());
        userActivityServiceImpl.save(userActivity);
        boolean r = userServiceImpl.deleteById(id);
        return r ? R.ok("成功删除交警账号.") : R.error("删除交警账号失败.");
    }

    //使用mybtis-plus实现批量删除
    @PostMapping("/del/batch/")
    public boolean deleteBatch(@RequestBody List<Integer> ids, HttpServletRequest request){
        if (null == ids || ids.size() == 0)
            return false;
        User currentOpUser = userServiceImpl.getOperateUser(request);

        // 批量删除前先保持
        for (Integer key :ids) {
            User user = userServiceImpl.getById(key);
            UserActivity userActivity = new UserActivity();
            BeanUtil.copyProperties(user, userActivity, true);
            userActivity.setUid(user.getId());
            Integer id = null;
            userActivity.setId(id);
            userActivity.setOperationType(OperationType.USER_DELETE_BULK.getDesc());
            userActivity.setReviser(currentOpUser.getUserName());
            userActivity.setRevisionTime(LocalDateTime.now());
            userActivityServiceImpl.save(userActivity);
        }

        return userServiceImpl.removeByIds(ids);
    }



    // 更新
    @PutMapping
    public Result updateById2(@RequestBody User user, HttpServletRequest request){


        User currentOpUser = userServiceImpl.getOperateUser(request);

        boolean res = userServiceImpl.saveOrUpdate2(user, currentOpUser);
        if (res) {
            // 更新后，写入历史表
            UserActivity userActivity = new UserActivity();
            BeanUtil.copyProperties(user, userActivity, true);
            userActivity.setOperationType(OperationType.USER_UPDATE.getDesc());
            userActivity.setUid(user.getId());
            Integer id = null;
            userActivity.setId(id);
            userActivity.setReviser(currentOpUser.getUserName());
            userActivity.setRevisionTime(LocalDateTime.now());
            // 设置更新时间
            userActivityServiceImpl.save(userActivity);
            return Result.success(ResponseCode.UPDATE_USER_SECCESS.getKey(), ResponseCode.UPDATE_USER_SECCESS.getDesc(), null);

        }else
            return Result.error(ResponseCode.UPDATE_USER_FAILURE.getKey(), ResponseCode.UPDATE_USER_FAILURE.getDesc());
    }

    public R updateById(@RequestBody User user, HttpServletRequest request){
        User currentOpUser = userServiceImpl.getOperateUser(request);
        return (userServiceImpl.saveOrUpdate2(user, currentOpUser)) ? R.ok("成功更新交警账号.") : R.error("更新交警账号失败.");
    }
    //查询翻页数据集
    @GetMapping("/page")
    public Map<String,Object> findPage(@RequestParam String policeId, @RequestParam String userName, @RequestParam Integer pageNum, @RequestParam Integer pageSize){
        pageNum = (pageNum-1) * pageSize;
        return userServiceImpl.findPage(policeId, userName, pageNum, pageSize);
    }

    public Map<String,Object> findPage2(@RequestParam Integer pageNum, @RequestParam Integer pageSize){
        pageNum = (pageNum-1) * pageSize;
        return userServiceImpl.findPage2(pageNum, pageSize);
    }

}

/*
import com.buaa.entity.User;
import com.buaa.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired(required = true)
    private UserServiceImpl userService;

    @PostMapping
    //使用mybtis-plus,注意这里返回的是boolean型
    public Boolean save(@RequestBody User user) {
        return userService.saveUser(user);
    }
}*/
  /*
    @RequestMapping("/test")
    public String login(){
        return "main.html";
    }
    @GetMapping("/")
    //Map方式
    public String index(Map<String, Object> map){
        map.put("msg", "Hello, Spring Boot!");
        return "login.html";
    }
    //Model 方式
    public String index(Model model){
        model.addAttribute("msg", "Hello 同学");
        return "login.html";
    }

    @PostMapping("/login")
    public String login(String username, String password) {
        System.out.println("用户名是:"+username+"密码是:"+password);
        return "main.html";
    }
    //    @GetMapping("/list")
//    public List<User> index(){
//        return userMapper.findAll();
//    }

//    @Autowired
//    private UserService userService;

    */